package com.doge.walknovel.business.home.genres.genres

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.doge.wnpro.R
import com.doge.walknovel.api.model.NovelInfo
import com.doge.walknovel.business.novel.NovelDetailActivity
import com.doge.walknovel.business.novel.NovelRefer
import com.doge.walknovel.core.BaseFragment
import com.doge.walknovel.core.base.adapters.ITEM_CLICKED
import com.doge.walknovel.core.base.isRefreshing
import com.doge.wnpro.databinding.FragmentGenresCellBinding

class GenresCellFragment : BaseFragment() {
    private var innerBinding: FragmentGenresCellBinding? = null
    private val binding get() = innerBinding!!
    private val requestId by lazy { arguments?.getInt(EXTRA_ID)!! }
    private val viewModel by viewModels<GenresCellViewModel> { GenresCellViewModelFactory(requestId) }
    private val adapter by lazy { GenresCellAdapter() }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        innerBinding =
            innerBinding ?: FragmentGenresCellBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.refreshLayout.setColorSchemeResources(R.color.pull_refresh)
        binding.refreshLayout.setOnRefreshListener {
            viewModel.request()
        }
        binding.recyclerView.itemAnimator = null
        binding.recyclerView.layoutManager = LinearLayoutManager(binding.recyclerView.context)
        binding.recyclerView.adapter = adapter
        adapter.setListener(::handleAdapterCallback)

        viewModel.loading.observe(viewLifecycleOwner) {
            binding.refreshLayout.isRefreshing = it.isRefreshing()
        }
        viewModel.dataList.observe(viewLifecycleOwner) {
            adapter.submitList(it)
        }
        viewModel.request()
    }


    private fun handleAdapterCallback(action: String, item: Any?) {
        when (action) {
            ITEM_CLICKED -> NovelDetailActivity.start(context, (item as? NovelInfo?)?.novelId, NovelRefer.genresCell, requestId)
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        binding.refreshLayout.setOnRefreshListener(null)
        binding.recyclerView.adapter = null
        adapter.setListener(null)
        innerBinding = null
    }

    companion object {
        private const val EXTRA_ID = "id"
        fun newInstance(id: Int): GenresCellFragment {
            return GenresCellFragment().apply {
                arguments = Bundle().apply {
                    putInt(EXTRA_ID, id)
                }
            }
        }
    }
}